// pages/order-pay/order-pay.js

import { URL, SER_KEY } from "../../config.js"
import { POST, GET } from "../../utils/request.js"
let event = require('../../utils/event.js');
Page({

  /**
   * 页面的初始数据         
   */
  data: {
    shopName:'',//店铺名称
    userDistance:'',//用户距离门店距离
    wayTabNum:'PS_WS',
    timeValues:[],
    chooseDateTime:[],
    isTimeBoxShow:false,
    cartList: [],//商品明细列表
    totalPrice:'',//购物车总价格
    discount:0,//首单折扣
    manJianPrice: 0,//满足满减的金额
    manJianPriceMinus: 0 ,//满减金额
    address:'',//店铺地址
    defaultDistance: 0,//默认配送距离
    ascendingDistance:0,//递增距离
    ascendingPrice: 0,//递增费用
    userPhone:'',
    timeIndex:0,
    time:'请选择时间',//配送时间
    date:'',//配送日期
    user:'',//自取昵称
    tel:'',//自取电话
    address:"",
    showAdd:false,
    selfLatitude:'',
    selfLongitude:'',
    realPrice:'',//实付价格
    postage:0,//配送费
    lsale: [],//优惠信息
    shop_id:'',//店铺id
    remarks:'',
    payType:'PAY_WEIXIN',
    addressId:'',//地址id
    storeMsg:{},
    accountMoney:'',//余额
    addressInfo:'',
    userDistance:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getPrepareOrder()
    var storeMsg = JSON.parse(wx.getStorageSync("shopData"))
    console.log(storeMsg)
    this.setData({
      storeMsg: storeMsg,
      userDistance:storeMsg.user_distance,
      wayTabNum:storeMsg.delivery_type=="SHOP_PEISONG_WS"||storeMsg.delivery_type=="SHOP_PEISONG_ZQ_AND_WS"?'PS_WS':'PS_ZQ'
    })
    let that=this
    if (that.data.selfLatitude==''&&that.data.wayTabNum=='PS_ZQ'){
      wx.getLocation({
        //type: 'wgs84',
        type: 'gcj02',
        success: function (res) {
          console.log(res)
          var latitude = res.latitude;
          var longitude = res.longitude;
          that.setData({
            selfLongitude: longitude,//经度
            selfLatitude: latitude,//纬度        
          });
        }
      })
    }
    console.log(that.data.wayTabNum)

    event.on('RefreshAddress', this, function (addressInfo) {
      // console.log(addressInfo)
      this.setData({
        user: addressInfo.name,
        tel: addressInfo.phone,
        address: addressInfo.address,
        addressInfo: addressInfo.address_info,
        lat: addressInfo.lat,
        lng: addressInfo.lng,
        showAdd:true,
        addressId: addressInfo.id
      })
    })
    
  },
  onUnload: function () {
    event.remove('RefreshAddress', this);
  },
  checkUserAddress(){
    let that=this
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY15;
    let data = {
      appId: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      addressId: this.data.addressId,
      shopId: this.data.shop_id
    };
    GET(url, data, (resData) => {
      console.log(resData.data.postage)
      if (resData.data.res == "FAIL"){
        wx.showToast({
          title: resData.data.errMsg,
          icon:'none'
        })
        this.setData({
          showAdd:false,
          
        })
      }else{        
        var postage = resData.data.postage
        let totalPrice = that.data.totalPrice
        let userDistance = resData.data.userDistance
        let delivery_price = that.data.storeMsg.delivery_price
        let free_postage = that.data.storeMsg.free_postage
        if (totalPrice > free_postage){
          postage = postage - delivery_price
        }                
        let endPrice = totalPrice + postage 
        console.log(free_postage, delivery_price, endPrice, postage, totalPrice)
        that.setData({
          postage: postage,
          realPrice: endPrice.toFixed(2),
          totalPrice: totalPrice, 
          userDistance:userDistance
        })
      }
            
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  chooseTime(e){
    // console.log(e.currentTarget.dataset.time)
    this.setData({
      time: e.currentTarget.dataset.time,
      date: e.currentTarget.dataset.day,
      isTimeBoxShow: false
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.data.user? this.checkUserAddress() : ''
  },
  checkSession(){
   
  },
  getPhoneNumber: function (e) {
    var _this = this
    wx.checkSession({
      　　　　success: function(res){
      　　　　　　console.log("处于登录态");
                if (e.detail.errMsg == "getPhoneNumber:ok") {
                  var iv = e.detail.iv
                  var encryptedData = encodeURIComponent(e.detail.encryptedData)
                      _this.getUserPhone( encryptedData, iv)
                }
      　　　　},
      　　　　fail: function(res){
      　　　　　　console.log("需要重新登录");
      　　　　　　wx.showToast({
                title: '登录过期',
              })
              setTimeout(function () {
                wx.navigateTo({
                  url: '/pages/authorized-login/authorized-login',
                })
               }, 1000)
      　　　　}
      　　})
    
  },
  //获取用户手机号码
  getUserPhone(encryptedData, iv){
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY10;
    let data = {
      appId: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      encryptedData: encryptedData,
      iv: iv
    };
    GET(url, data, (resData) => {
      console.log(resData)
      if (resData.data.res=='SUCCESS'){
        this.setData({
          userPhone: resData.data.userPhone
        })
      }else{
        wx.showToast({
          title: resData.data.errMsg,
          icon:'none'
        })
      }
      
    })
  },
  getPrepareOrder(){
    let that=this
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY11;
    let data = {
      appId: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      shopId:wx.getStorageSync('id')
    };
    GET(url, data, (resData) => {
      console.log(resData)
      that.setData({
        chooseDateTime: resData.data.chooseDateTime,
        cartList: resData.data.lproduct,
        realPrice: resData.data.totalPrice,
        postage: resData.data.postage,
        accountMoney: resData.data.accountMoney,
        // lsale: resData.data.lsale,
        shop_id: resData.data.lproduct[0].shop_id,
        totalPrice: resData.data.totalPrice
      })
    })
  },
  chooseDate(e){
    console.log(e.currentTarget.dataset.index)
    this.setData({
      timeIndex:e.currentTarget.dataset.index
    })
  },
  //创建订单
  creatOrder(){
    let that = this
    const {wayTabNum,payType,addressId,realPrice,postage,userPhone,time}=that.data
    console.log(time)
    if (time =='请选择时间'){
      wx.showToast({
        title: '请选择时间',
        icon:'none'
      })
      return;
  }
    if (!that.data.showAdd&&wayTabNum=='PS_WS'){
      wx.showToast({
        title: '请选择收获地址',
        icon: 'none'
      })
      return;
    }
    if(userPhone==''&&wayTabNum=='PS_ZQ'){
      wx.showToast({
        title: '请添加联系方式',
        icon: 'none'
      })
      return;
    }
    let url = URL.HTTP_BASE_INTRANET + SER_KEY.SER_KEY17;
    let data = {
      appId: getApp().globalData.appId,
      sessionId: wx.getStorageSync('session_id'),
      shopId: wx.getStorageSync('id'),
      deliveryType: wayTabNum,
      payType: payType,
      addressId:addressId,
      price: realPrice,
      postage: postage,
      sendDateTime: that.data.date +'\xa0'+that.data.time,
      userPhone: userPhone,
      userLat: that.data.selfLatitude,
      userLng: that.data.selfLongitude,
      note: that.data.remarks
    };
    console.log(data)
    GET(url, data, (resData) => {
      console.log(resData.data.pay)
      if (resData.data.res =='SUCCESS'){
        let datas = resData.data.pay
        wx.requestPayment(
          {
            'timeStamp': datas.timeStamp,
            'nonceStr': datas.nonceStr,
            'package': datas.package,
            'signType': 'MD5',
            'paySign': datas.paySign,
            'success': function (res) { 
              console.log(res)
              wx.navigateTo({
                url: '/pages/pay-successed/pay-successed?id='+resData.data.orderId+'&price='+that.data.totalPrice,
              })
            },
            'fail': function (res) { 
              console.log(res)
              wx.switchTab({
                url: '/pages/orders/orders',
              })
            },
            'complete': function (res) {
             }
          })
      }else{
        wx.showToast({
          title: resData.data.errMsg ,
          icon:'none'
        })
      }
    })
  },
  // 导航
  location() {
    let that = this
    console.log(that.data.storeMsg)
    let address = that.data.storeMsg.shop_address
    console.log(address)
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        wx.openLocation({
          latitude: latitude,
          longitude: longitude,
          name: address,
          scale: 28
        })
      }
    })
  },
  // 切换外送方式
  tabDeliveryWay: function (e) {
    let that = this
    if (e.currentTarget.dataset.text === '外送') {
      that.setData({
        wayTabNum: 'PS_WS'
      })
    } else if (e.currentTarget.dataset.text === '自取') {
      if (that.data.selfLatitude==''){
        wx.getLocation({
          //type: 'wgs84',
          type: 'gcj02',
          success: function (res) {
            console.log(res)
            var latitude = res.latitude;
            var longitude = res.longitude;
            that.setData({
              selfLongitude: longitude,//经度
              selfLatitude: latitude,//纬度        
            });
          }
        })
      }
      that.setData({
        wayTabNum: 'PS_ZQ'
      })
    }
  },
  // 选择支付方式
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      payType: e.detail.value
    })
  },
  // 显示时间box
  showTimeBox: function () {
    this.setData({
      isTimeBoxShow: true
    })
  },
  // 关闭时间box
  closeTimeBox: function () {
    this.setData({
      isTimeBoxShow: false
    })
  }
})